/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.mq.timerTask;

import cn.ac.iie.di.wx.mq.common.RuntimeEnv;
import static cn.ac.iie.di.wx.mq.common.RuntimeEnv.jsonMaxNum;
import static cn.ac.iie.di.wx.mq.common.RuntimeEnv.retryQueue;
import cn.ac.iie.di.wx.mq.httpservice.HttpSender;
import cn.ac.iie.di.wx.mq.utils.RedisUtil;
import cn.ac.iie.di.wx.mq.vo.RedisVo;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Austin
 */
public class RetryFileThread implements Runnable {

    static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RetryFileThread.class.getName());

    public RetryFileThread() {
    }

    @Override
    public void run() {
        //改成写文件
        logger.info("RetryTask start");
        try {
            while (true) {
                Thread.sleep(1000);
                logger.info("RetryTask run");
                int size = RuntimeEnv.retryQueue.size();
                if (size == 0) {
                    continue;
                }
                logger.info("retry size is: " + size);
                int count = 1;
                String root = System.getProperty("user.dir");
                String filePath = root + "/" + "redo/";
                File path = new File(filePath);
                if (!path.isDirectory() || !path.exists()) {
                    path.mkdirs();
                    logger.info("create new path name = " + filePath);
                }
                String fileName = filePath + System.currentTimeMillis() / 1000 + "_retry.txt";
                logger.info("fileName is " + fileName);
                File file = new File(fileName);
                if (!file.exists()) {
                    file.createNewFile();
                    logger.info("create new file name = " + fileName);
                }
                FileWriter writer = null;
                //1000条一个文件
                int jsonMaxNum = Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.jsonMaxNum));
                while (count <= jsonMaxNum) {
                    //logger.info("try "+i);
                    RedisVo vo = RuntimeEnv.retryQueue.poll(500, TimeUnit.MILLISECONDS);
                    if (vo == null) {
                        break;
                    } else {
                        //写完后在文件名后添加完成标志
                        try {
                            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件     
                            writer = new FileWriter(file, true);
                            PrintWriter pw = new PrintWriter(writer);
                            pw.println(vo.getOpid() + "|" + vo.getRedisValue() + "|" + vo.getRequestJson());
                            pw.flush();
                            writer.flush();
                            pw.close();
                            writer.close();
                            count++;
                        } catch (IOException e) {
                            logger.error(e.getMessage(), e);
                        } finally {
                            try {
                                if (writer != null) {
                                    writer.close();
                                }
                            } catch (IOException e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                }
                //将文件重命名，加上完成标志
                String finishFileName = fileName + ".ok";
                File finishFile = new File(finishFileName);
                file.renameTo(finishFile);
                logger.info("finish finishFileName = " + finishFileName);
            }
        } catch (Exception e) {
            logger.error("RetryThread class error : " + e.getMessage(), e);
        }

    }

}
